import { firstToUpper, isEmpty } from 'howtools';
import { ref } from 'vue';
import { parserParams, parserResponse } from '@/utils/swigger';
// import { definitions } from '@/views/Home/hooks/docsObj';
export function useGenCode() {
    const genCodeVisible = ref(false)

    return {
        genCodeVisible
    }
}

export function useBatchGenCode() {
    const genBatchCodeVisible = ref(false)

    return {
        genBatchCodeVisible
    }
}


/**
 * @param  {string} url 链接
 * @param  {string} method 方法
 * @param  {string} content 原始代码模板
 */
export interface CodeOption {
    url: string; method: string; summary: string; params: AnyObject; response: AnyObject
}
/**
 * @param  {string} key
 * @description 转换java类型为ts类型
 */
function typeTransform(key: string) {
    const obj: Record<string, string> = {
        'integer': 'number',
        'array': '[]',
    }
    return obj[key] || key
}

/**
 * @param  {string} url 请求URL
 * @param  {any} params 参数列表 header body query 等
 */
function getTsCode(url: string, params: any, response: AnyObject) {
    let queryInterface: string[] = [];
    let bodyInterface: string[] = [];
    let respInterface: string[] = []
    const { query, body } = parserParams(params)
    const _gen_type_line = (k: string, v: string, desc: string) => `${k}: ${v}; //${desc || '-'}`

    // params
    const queryInterfaceName = `${firstToUpper(urlToFuncName(url))}QueryOptions`
    queryInterface.push(`export interface ${queryInterfaceName} {`)
    for (const q of query) {
        const { description, type: v, name: k } = q
        queryInterface.push(`  ${_gen_type_line(k, typeTransform(v), description)}`)
    }
    queryInterface.push("}\n")


    //body
    const bodyInterfaceName = `${firstToUpper(urlToFuncName(url))}BodyOptions`
    bodyInterface.push(`export interface ${bodyInterfaceName} {`)
    for (const q of body) {
        const { description, type: v, name: k } = q
        bodyInterface.push(`  ${_gen_type_line(k, typeTransform(v), description)}`)
    }
    bodyInterface.push("}\n")

    // Resp
    // 只解析状态值为200的情况
    const resp = parserResponse(response["200"])

    const respInterfaceName = `${firstToUpper(urlToFuncName(url))}ResponseOpts`
    let genCount = 0; // 第几次生成genCount
    function _genResponse(resp: any[], respInterfaceName: string, type: "array" | "object" | "string" | "number" | undefined) {
        genCount += 1
        const count = genCount
        if (count === 1) {
            respInterface.push(`export interface ${respInterfaceName} {`)
        } else {
            respInterface.push(`${respInterfaceName}: {`)
        }

        for (const r of resp) {
            const { description, type: v, name: k, sub = [] } = r
            if (sub.length > 0) {
                _genResponse(sub, `${'  '.repeat(count)}${k}`, v)
                continue
            }
            respInterface.push(`${'  '.repeat(count)}${_gen_type_line(k, typeTransform(v), description)}`)
        }

        if (type === "array") {
            count === 1 ? respInterface.push(`${'  '.repeat(count - 1)}}[]`) : respInterface.push(`${'  '.repeat(count - 1)}}[];`)
        } else {
            count === 1 ? respInterface.push(`${'  '.repeat(count - 1)}}`) : respInterface.push(`${'  '.repeat(count - 1)}};`)
        }
    }
    _genResponse(resp, respInterfaceName, undefined)

    return {
        query: !isEmpty(queryInterface) ? queryInterface.join("\n") : "",
        body: !isEmpty(bodyInterface) ? bodyInterface.join("\n") : "",
        resp: !isEmpty(respInterface) ? respInterface.join("\n") : "",
        bodyInterfaceName,
        queryInterfaceName,
        respInterfaceName,
    }
}

// 和tscode 方法类似，这里生成一个json对象，方便复制使用。
export function getTsCodeJson(url: string, params: any, response: AnyObject) {
    let queryJson: string[] = [];
    let bodyJson: string[] = [];
    let respJson: string[] = []
    const { query, body } = parserParams(params)
    const _gen_type_line = (k: string, v: string, desc: string) => {
        if (v === "object") {
            return `${k}: {}, //${desc || '-'}`
        }

        if (v === "array" || v === "[]") {
            return `${k}: [], //${desc || '-'}`
        }

        if (v == "number") {
            return `${k}: 0, //${desc || '-'}`
        }

        if (v == "string") {
            return `${k}: "", //${desc || '-'}`
        }

        return `${k}: ${v}, //${desc || '-'}`
    }

    // params
    const queryJsonName = `const ${urlToFuncName(url)}QueryJson =`
    queryJson.push(`${queryJsonName} {`)
    for (const q of query) {
        const { description, type: v, name: k } = q
        queryJson.push(`  ${_gen_type_line(k, typeTransform(v), description)}`)
    }
    queryJson.push("}\n")


    //body
    const bodyJsonName = `const ${urlToFuncName(url)}BodyJson =`
    bodyJson.push(`${bodyJsonName} {`)
    for (const q of body) {
        const { description, type: v, name: k } = q
        bodyJson.push(`  ${_gen_type_line(k, typeTransform(v), description)}`)
    }
    bodyJson.push("}\n")

    // Resp
    // 只解析状态值为200的情况
    const resp = parserResponse(response["200"])

    const respJsonName = `const ${urlToFuncName(url)}ResponseJson =`
    let genCount = 0; // 第几次生成genCount
    function _genResponse(resp: any[], respJsonName: string, type: "array" | "object" | "string" | "number" | undefined) {
        genCount += 1
        const count = genCount
        if (count === 1) {
            respJson.push(`${respJsonName} {`)
        } else {
            if (type === "array") {
                respJson.push(`${respJsonName}: [{`)
            } else {
                respJson.push(`${respJsonName}: {`)
            }
        }
        for (const r of resp) {
            const { description, type: v, name: k, sub = [] } = r
            if (sub.length > 0) {
                _genResponse(sub, `${'  '.repeat(count)}${k}`, v)
                continue
            }
            respJson.push(`${'  '.repeat(count)}${_gen_type_line(k, typeTransform(v), description)}`)
        }

        if (type === "array") {
            respJson.push(`${'  '.repeat(count - 1)}}],`)
        } else {
            respJson.push(`${'  '.repeat(count - 1)}}`)
        }
    }
    _genResponse(resp, respJsonName, undefined)

    return {
        query: !isEmpty(queryJson) ? queryJson.join("\n") : "",
        body: !isEmpty(bodyJson) ? bodyJson.join("\n") : "",
        resp: !isEmpty(respJson) ? respJson.join("\n") : "",
        bodyJsonName,
        queryJsonName,
        respJsonName,
    }
}

/**
 * @param  {string} url 
 * @description 根据URL 生成函数名称
 */
function urlToFuncName(url: string) {
    const nameArr =
        url
            .replace("{", "")
            .replace("}", "")
            .match(/\/(.*?)\w+/g) || [];

    return (nameArr[nameArr.length - 1] || "").replace("/", "");
}

/**
 * @param  {CodeOption[]} options 代码
 * @param  {string} content 代码模板 
 *  url 请求连接 method 请求方法 name 请求名称 summary 方法说明
 */
export function getCode(option: CodeOption, content: string) {
    if (!option.url) return
    // 生成方法名称
    const name = urlToFuncName(option.url);

    const { body: bodyInterface, query: queryInterface, resp: respInterface, bodyInterfaceName, queryInterfaceName, respInterfaceName } = getTsCode(option.url, option.params, option.response)

    //内容解析
    const c = content
        .replace(/{{ url }}/g, option.url)
        .replace(/{{ method }}/g, option.method.toUpperCase())
        .replace(/{{ name }}/g, name)
        .replace(/{{ summary }}/g, option.summary)
        .replace(/{{ bodyInterfaceName }}/g, bodyInterfaceName)
        .replace(/{{ queryInterfaceName }}/g, queryInterfaceName)
        .replace(/{{ respInterfaceName }}/g, respInterfaceName)
        .trim()

    return [bodyInterface, queryInterface, respInterface, c].join("\n")
}

export function getJson(option: CodeOption, content: string) {
    if (!option.url) return
    // 生成方法名称
    // const name = urlToFuncName(option.url);

    const { body: bodyJson, query: queryJson, resp: respJson } = getTsCodeJson(option.url, option.params, option.response)


    return [bodyJson, queryJson, respJson].join("\n")
}

// 获得一个纯的json代码
export function getPureJsonCode(option: CodeOption, content: string) {
    if (!option.url) return
    // 生成方法名称
    // const name = urlToFuncName(option.url);

    const { body: bodyJson, query: queryJson, resp: respJson } = getTsCodeJson(option.url, option.params, option.response)


    return [bodyJson, queryJson, respJson].join("\n")
}

export function getJsonData(option: CodeOption, content: string) {
    const { query, body } = parserParams(option.params)
    const resp = parserResponse(option.response["200"])
    return {
        query,
        body,
        resp,
    }
}